import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

// 导入组件,以下这些没有用路由懒加载
// import login from '@/views/login'
// import layout from '@/layout'
// import home from '@/views/home'
// import ask from '@/views/ask'
// import video from '@/views/video'
// import mine from '@/views/mine'
// import edit from '@/views/mine/edit'
// import article from '@/views/article'
// import search from '@/views/search'
// import result from '@/views/search/result'
// import chat from '@/views/chat'


// 下面这些路由懒加载的写法
const login =  () => import( '@/views/login')
const layout =  () => import( '@/layout')
const home =  () => import( '@/views/home')
const ask =  () => import( '@/views/ask')
const video =  () => import( '@/views/video')
const mine =  () => import( '@/views/mine')
const edit =  () => import( '@/views/mine/edit')
const article =  () => import( '@/views/article')
const search =  () => import( '@/views/search')
const result =  () => import( '@/views/search/result')
const chat =  () => import( '@/views/chat')

const routes = [
  // 路由重定向
  { path: '', redirect: '/layout/home' },
  { name: 'login', path: '/login', component: login },
  // 聊天机器人组件
  { name: 'chat', path: '/mine/chat', component: chat },
  { name: 'search', path: '/search', component: search },
  { name: 'article', path: '/article', component: article },
  { name: 'result', path: '/search/result', component: result, meta: { needKeep: true } },
  // 这里的路径是为了让用户看起来知道这是我的资料的修改
  { name: 'edit', path: '/mine/edit', component: edit },
  {
    name: 'layout',
    path: '/layout',
    component: layout,
    children: [
      { name: 'home', path: 'home', component: home, meta: { needKeep: true } },
      { name: 'ask', path: 'ask', component: ask },
      { name: 'video', path: 'video', component: video },

      {
        name: 'mine',
        path: 'mine',
        component: mine,
        // meta：路由元信息（其实就是给路由打个标记）
        meta: {
          needLogin: true
        }
      },
    ]
  },
]

const router = new VueRouter({
  routes
})


// 导入store
import store from '@/store'
// 路由：全局前置守卫
// 在即将进入某个路由之前调用
// to：你要去哪的路由信息
// from：你从哪来路由信息
// next：是一个函数，调用next代表放行(放行的的意思是让你访问这个路由)
router.beforeEach((to, from, next) => {

  // 判断去的是不是需要登录的页面
  if (to.meta.needLogin) {
    // 是需要登录的页面
    // 判断有没有token（判断vuex里有没有token）
    if (store.state.tokenObj.token) {
      // 如果有token放行
      next()

    } else {
      // 否则打回登录页
      // 弹出提示
      Vue.prototype.$toast.fail('请先登录')
      // 放行到登录页，还要加参数，加一个原本我想去的页面的路径
      next('/login?back=' + to.path)
    }

  } else {

    // 不需要登录的页面，直接放行
    next()
  }

})


// // vue-router3.1后新增了一些跳转的警告
// // 如果不想出现这些警告，使用如下代码即可把报错吞掉
// const routerPush = VueRouter.prototype.push
// VueRouter.prototype.push = function push(location) {
//   return routerPush.call(this, location).catch(error=> error)
// }


export default router
